package com.xncoding.jwt.config.handler;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ClientNio {
    public static void main(String[] args) {
        client();
    }

    public static void client() {
        // 单线程池
        ExecutorService single = Executors.newSingleThreadExecutor();
        ByteBuffer readBuffer = ByteBuffer.allocateDirect(1024);
        ByteBuffer writeBuffer = ByteBuffer.allocateDirect(1024);
        // 开启选择器 socket scanner(用来发送消息)
        try (Selector selector = Selector.open();
             SocketChannel sc = SocketChannel.open();
             Scanner scanner = new Scanner(System.in)) {
            sc.configureBlocking(false);
            // 建立连接的地址
            sc.connect(new InetSocketAddress("localhost", 10010));
            // 注册连接事件
            sc.register(selector, SelectionKey.OP_CONNECT);
            while (true) {
                selector.select();
                Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
                while (keys.hasNext()) {
                    SelectionKey key = keys.next();
                    // 连接事件且连接完成后,注册读事件和写事件
                    if (key.isConnectable()) {
                        if (sc.finishConnect()) {
                            sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                        }
                    }
                    // 读事件
                    if (key.isReadable()) {
                        // 读取服务端数据
                        readBuffer.clear();
                        int read = sc.read(readBuffer);
                        byte[] readByte = new byte[read];
                        readBuffer.flip();
                        readBuffer.get(readByte);
                        System.out.println(new String(readByte));
                        // 重新注册写事件
                        key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
                    }
                    // 写事件
                    if (key.isWritable()) {
                        // 使用线程写数据到服务端
                        threadWrite(single, writeBuffer, sc, scanner);
                        // 取消注册写事件(不取消会造成上一次数据可能还没发送,下次进来还会继续执行)
                        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                    }
                    // 移除key
                    keys.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void threadWrite(ExecutorService single, ByteBuffer writeBuffer, SocketChannel sc, Scanner scanner) {
        single.execute(() -> {
            try {
                // 休眠
                TimeUnit.SECONDS.sleep(1);
                // 使用scanner读取控制台输入
                System.out.println(Thread.currentThread().getName() + "请输入:");
                String line = scanner.nextLine();
                writeBuffer.put(line.getBytes());
                writeBuffer.flip();
                // 写入数据
                while (writeBuffer.hasRemaining()) {
                    sc.write(writeBuffer);
                }
                writeBuffer.compact();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

}